package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.CartAddUuBean;
import com.atguigu.func.MyWindowFunction;
import com.atguigu.uitl.ClickHouseUtil;
import com.atguigu.uitl.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hjy
 * @create 2023/3/17 20:15
 */
public class Dws06_TradeCartAddUuWindow {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HAOOP_USER_NAME","atguigu");
        //todo 2 从kafka（dwd_cart_info）读数据
        String topic="dwd_cart_info";
        String groupID="trade_cart_add_0926";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupID));

        //todo 3 将数据转为JSONObj对象 并提取时间戳
        SingleOutputStreamOperator<JSONObject> jsonObjWithWMDS = kafkaDS.map(JSONObject::parseObject)
                .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                return element.getLong("create_time");
                            }
                        })));

        //todo 4 按照uid分组
        KeyedStream<JSONObject, String> keyedStream = jsonObjWithWMDS.keyBy(value -> value.getString("user_id"));

        //todo 5 转为javaBean对象
        SingleOutputStreamOperator<CartAddUuBean> cartAddUuBeanDS = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, CartAddUuBean>() {
            private ValueState<String> lastCartDtState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlCfg = StateTtlConfig.newBuilder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build();
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("last_cart_dt", String.class);
                valueStateDescriptor.enableTimeToLive(ttlCfg);

                lastCartDtState = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public void flatMap(JSONObject value, Collector<CartAddUuBean> out) throws Exception {
                String lastDt = lastCartDtState.value();
                String curtDt = value.getString("create_time").split(" ")[0];
                Long uu = 0L;
                if (lastDt == null || !lastDt.equals(curtDt)) {
                    uu = 1L;
                    lastCartDtState.update(curtDt);
                }
                if (uu == 1L) {
                    out.collect(new CartAddUuBean("",
                            "",
                            uu,
                            null));
                }
            }
        });
        //todo 6 开窗聚合
        SingleOutputStreamOperator<CartAddUuBean> resultDS = cartAddUuBeanDS.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<CartAddUuBean>() {
                    @Override
                    public CartAddUuBean reduce(CartAddUuBean value1, CartAddUuBean value2) throws Exception {
                        value1.setCartAddUuCt(value1.getCartAddUuCt() + value2.getCartAddUuCt());
                        return value1;
                    }
                }, new AllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<CartAddUuBean> values, Collector<CartAddUuBean> out) throws Exception {
                        CartAddUuBean next = values.iterator().next();
                        out.collect(MyWindowFunction.getJavaBeanField(next, window));
                    }
                });
        //todo 7 数据写入clickHouse
        resultDS.print("resultDS>>>>>>>>>>");
        resultDS.addSink(ClickHouseUtil.getSinkFunction("insert into dws_trade_cart_add_uu_window values(?,?,?,?)"));
        //todo 8 启动程序
        env.execute("Dws06_TradeCartAddUuWindow");

    }
}
